package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.enums.YesOrNoEnum;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    @Override
    @Transactional
    public void addAddressBook(AddressBookUpsertReqDTO dto) {
        AddressBook addressBook = BeanUtil.copyProperties(dto, AddressBook.class);
        addressBook.setUserId(UserContext.currentUser().getId());
        //处理经纬度
        handleLocation(dto.getLocation(), addressBook);
        if(dto.getIsDefault() == YesOrNoEnum.YES.getStatus()){
            //当前是默认的，需要将其他的设置为非默认
            lambdaUpdate()
                    .eq(AddressBook::getUserId, UserContext.currentUser().getId())
                    .set(AddressBook::getIsDefault, YesOrNoEnum.NO.getStatus())
                    .update();
        }
        boolean result = save(addressBook);
        if (!result){
            throw new RuntimeException("新增地址薄失败");
        }
    }

    private void handleLocation(String location, AddressBook addressBook) {
        if(StrUtil.isNotEmpty(location)){
            String[] split = location.split(",");
            addressBook.setLon(NumberUtils.parseDouble(split[0]));
            addressBook.setLat(NumberUtils.parseDouble(split[1]));
        }
    }

    @Override
    public PageResult<AddressBookResDTO> page(AddressBookPageQueryReqDTO dto) {
        Page<AddressBook> page = PageUtils.parsePageQuery(dto, AddressBook.class);
        Page<AddressBook> addressBookPage = baseMapper.selectPage(page, Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId()));
        return PageUtils.toPage(addressBookPage, AddressBookResDTO.class);
    }

    @Override
    @Transactional
    public void editAddressBook(AddressBookUpsertReqDTO dto, Long id) {
        AddressBook addressBook = getById(id);
        if(ObjectUtil.isEmpty(addressBook)){
            throw new BadRequestException("地址薄不存在");
        }
        BeanUtil.copyProperties(dto, addressBook);
        handleLocation(dto.getLocation(),addressBook);
        if(dto.getIsDefault() == YesOrNoEnum.YES.getStatus()){
            //当前是默认的，需要将其他的设置为非默认
            lambdaUpdate()
                    .eq(AddressBook::getUserId, UserContext.currentUser().getId())
                    .set(AddressBook::getIsDefault, YesOrNoEnum.NO.getStatus())
                    .update();
        }
        boolean result = updateById(addressBook);
        if (!result){
            throw new ForbiddenOperationException("修改地址薄失败");
        }
    }

    @Override
    @Transactional
    public void deleteAddressBook(List<Long> ids) {
        boolean result = removeByIds(ids);
        if (!result){
            throw new ForbiddenOperationException("批量删除地址薄失败");
        }
    }

    @Override
    public void defaultAddressBook(Long id, Integer flag) {
        AddressBook addressBook = getById(id);
        if(ObjectUtil.isEmpty(addressBook)){
            throw new BadRequestException("地址薄不存在");
        }
        if (flag == YesOrNoEnum.YES.getStatus()){
            //当前是默认的，需要将其他的设置为非默认
            lambdaUpdate()
                    .eq(AddressBook::getUserId, UserContext.currentUser().getId())
                    .set(AddressBook::getIsDefault, YesOrNoEnum.NO.getStatus())
                    .update();
        }
        boolean result = lambdaUpdate().eq(AddressBook::getId, id)
                .set(AddressBook::getIsDefault, flag)
                .update();
        if (!result){
            throw new ForbiddenOperationException("设置/取消默认地址失败");
        }
    }

    @Override
    public AddressBookResDTO getDefaultAddressBook() {
        AddressBook addressBook = lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDefault, YesOrNoEnum.YES.getStatus())
                .one();
        return BeanUtils.copyProperties(addressBook, AddressBookResDTO.class);
    }
}
